package com.andong;

import javafx.application.Application;

import java.io.*;
import java.sql.Timestamp;
import java.util.ArrayList;

public class FileUtil {

	/**
	 * 传入一个文件夹的绝对路径字符串, 创建所有路径上不存在的文件夹
	 *
	 * @param folderPath
	 * @return 文件夹已经存在返回false, 创建成功返回true
	 */
	public static boolean makePathDirs(String folderPath) {
		File file = new File(folderPath);
		if (!file.exists()) {
			return file.mkdirs();
		}
		return false;
	}

	/**
	 * 传入一个文件夹的绝对路径字符串, 创建所有路径上不存在的文件夹
	 *
	 * @param folderPath
	 * @return 文件夹已经存在返回false, 创建成功返回true
	 */
	public static boolean dirExist(String folderPath) {
		File file = new File(folderPath);
		if (!file.exists()) {
			return false;
		}
		return true;
	}

	/**
	 * 取指定文件夹下,指定类型的文件列表
	 * @param fileFolderPath 文件夹路径
	 * @param extentionName 文件扩展名
	 * @return
	 */
	public static String[] getFileNameList(String fileFolderPath,String extentionName) {
		if (FileUtil.dirExist(fileFolderPath)) {
			File folder = new File(fileFolderPath);
			if (folder.isDirectory()) {
				String[] fileList = folder.list((dir, name) -> {
					if (name.length() > extentionName.length()) {
						return (new File(dir, name)).isFile() &&
								name.substring(name.length() - 4).equalsIgnoreCase(extentionName);
					} else {
						return false;
					}
				});
				return fileList;
			}
		}
		return null;
	}

	/**
	 * 取文件扩展名(包括点号)
	 *
	 * @param file_name 文件名
	 * @returns {string}
	 */
	public static String getExtension (String file_name) {
		int indexExt = file_name.lastIndexOf('.');
		String result = (0 <= indexExt) ? file_name.substring(indexExt) : "";
		return result;
	}

	/**
	 * 按行读取 .txt 文件到列表中
	 * @param fileName
	 * @return
	 */
	public static ArrayList<String> readTxtLines(String fileName) {
		ArrayList<String> txtLines = new ArrayList<>();
		try {
			FileInputStream fileInputStream = new FileInputStream(fileName);
			InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			try {
				String aLine;
				while ((aLine = bufferedReader.readLine()) != null) {
					txtLines.add(aLine);
				}
				bufferedReader.close();
				inputStreamReader.close();
				fileInputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		finally {
			return txtLines;
		}
	}
	/**
	 * 将文本内容写入文本文件
	 *
	 * @param fileFolderPath
	 * @param textContent
	 */
	public static String writeTxt(String fileFolderPath, String textContent) {
		FileWriter fw;
		makePathDirs(fileFolderPath);
		String filePath = fileFolderPath + File.separator + System.currentTimeMillis() + ".txt";
		try {
			fw = new FileWriter(filePath);
			BufferedWriter bw = new BufferedWriter(fw);
			bw.write(textContent);
			bw.flush();
			bw.close();
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return filePath;
	}
}
